package com.usefullc.extinguisher.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.common.util.XlsUtils;
import com.usefullc.extinguisher.domain.FireDevice;
import com.usefullc.extinguisher.domain.FireDeviceAuditRecord;
import com.usefullc.extinguisher.enums.DeviceAuditRecordStatusEnum;
import com.usefullc.extinguisher.mapper.FireDeviceAuditRecordMapper;
import com.usefullc.extinguisher.query.FireDeviceAuditRecordQuery;
import com.usefullc.extinguisher.query.FireDeviceQuery;
import com.usefullc.extinguisher.vo.FireDeviceAuditRecordVo;
import com.usefullc.extinguisher.vo.FireDeviceVo;
import com.usefullc.system.domain.DataDict;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.query.DataDictQuery;
import com.usefullc.system.service.AbstractBizService;
import com.usefullc.system.service.DataDictService;
import com.usefullc.system.service.IPageMutilCallback;
import com.usefullc.user.domain.User;
import com.usefullc.user.query.UserQuery;
import com.usefullc.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.data.annotation.AccessType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备检查作业记录服务类
 * @author: 星空
 * @date: 2022-09-08
 */
@Service
public class FireDeviceAuditRecordService extends AbstractBizService<FireDeviceAuditRecordMapper, FireDeviceAuditRecord, FireDeviceAuditRecordQuery> {

    @Autowired
    private FireDeviceService fireDeviceService;

    @Autowired
    private UserService userService;

    @Autowired
    private DataDictService dataDictService;

    @Value("classpath:xlsTemplate/fireDeviceAudit.xls")
    Resource deviceXlsTemplate;

    @Override
    protected QueryWrapper<FireDeviceAuditRecord> getQueryWrapper(FireDeviceAuditRecordQuery query) {
        QueryWrapper<FireDeviceAuditRecord> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<FireDeviceAuditRecordVo> findVoByPage(FireDeviceAuditRecordQuery query){
        Pager<FireDeviceAuditRecord> page = this.findByPage(query);
        Pager<FireDeviceAuditRecordVo> newPage = new Pager<>(page);
        List<FireDeviceAuditRecord> dataList = page.getDataList();
        List<FireDeviceAuditRecordVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (FireDeviceAuditRecord fireDeviceAuditRecord : dataList) {
            FireDeviceAuditRecordVo fireDeviceAuditRecordVo = BeanUtils.beanCopy(fireDeviceAuditRecord, FireDeviceAuditRecordVo.class);
            newDataList.add(fireDeviceAuditRecordVo);
        }
        return newPage;
    }

    public Pager<FireDeviceAuditRecordVo> findNewByPage(FireDeviceAuditRecordQuery query){
        Pager<FireDeviceAuditRecordVo> page = this.findMultiByPage(query, new IPageMutilCallback<FireDeviceAuditRecordVo>() {
            @Override
            public Long count(QueryWrapper wrapper) {
                return getBaseMapper().selectByPageCount(wrapper);
            }
            @Override
            public IPage<FireDeviceAuditRecordVo> page(Page<FireDeviceAuditRecordVo> page, QueryWrapper wrapper) {
                return getBaseMapper().selectByPage(page,wrapper);
            }
        });
//        Pager<FireDeviceAuditRecordVo> newPage = new Pager<>(page);
        List<FireDeviceAuditRecordVo> dataList = page.getDataList();
//        List<FireDeviceAuditRecordVo> newDataList = new ArrayList<>();
//        newPage.setDataList(newDataList);
        for (FireDeviceAuditRecordVo fireDeviceAuditRecord : dataList) {

            Long deviceId = fireDeviceAuditRecord.getDeviceId();
            FireDevice fireDevice = fireDeviceService.findById(deviceId);

            FireDeviceVo fireDeviceVo = fireDeviceService.entityToFullVo(fireDevice);
            fireDeviceAuditRecord.setFireDeviceVo(fireDeviceVo);
//            FireDeviceAuditRecordVo fireDeviceAuditRecordVo = BeanUtils.beanCopy(fireDeviceAuditRecord, FireDeviceAuditRecordVo.class);
//            newDataList.add(fireDeviceAuditRecordVo);
        }
        return page;

    }



    public void export(FireDeviceAuditRecordQuery query, HttpServletResponse response) {
//        long total = this.count(query);
//        if (total > 3000) {
//            throw new BizException("批量导出不能大于3000");
//        }
        List<FireDeviceAuditRecord> dataList = this.findAll(query);
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
//        List<FireDevice> dataList = dataList
        List<List<Object>> xlsDataList = new ArrayList<>();
        xlsDataList.add(new ArrayList<>());
        xlsDataList.add(new ArrayList<>());
//        xlsDataList.add(Arrays.asList(headers));
        int orderNo = 1;
        Map<String, DataDict> deviceTypeDataDictMap = new HashMap<>();
        Map<Long, User> userMap = new HashMap<>();
        Map<String,DataDict> codeDataDictMap = new HashMap<>();
        Map<Long,DataDict> idDataDictMap = new HashMap<>();
//        DataDictQuery dataDictQuery = new DataDictQuery();
//        dataDictQuery.setCodeLike("0026");
        List<DataDict> dataDictList = dataDictService.findAll(new DataDictQuery());

        for (DataDict dataDict : dataDictList) {
            codeDataDictMap.put(dataDict.getCode(),dataDict);
            idDataDictMap.put(dataDict.getId(),dataDict);
            if(!dataDict.getCode().startsWith("0026")){
                continue;
            }
            deviceTypeDataDictMap.put(dataDict.getValue(),dataDict);
        }
        List<User> userList = userService.findAll(new UserQuery());
        for (User user : userList) {
            userMap.put(user.getId(),user);
        }

        List<FireDevice> fireDeviceList = new ArrayList<>();
        List<Long> fireDeviceIds = new ArrayList<>();
        for (FireDeviceAuditRecord fireDeviceAuditRecord : dataList) {
            fireDeviceIds.add(fireDeviceAuditRecord.getDeviceId());
            if(fireDeviceIds.size() >= 200){
                FireDeviceQuery fireDeviceQuery = new FireDeviceQuery();
                fireDeviceQuery.setIds(fireDeviceIds);
                List<FireDevice> fireDevices = fireDeviceService.findAll(fireDeviceQuery);
                fireDeviceList.addAll(fireDevices);
                fireDeviceIds.clear();
            }
        }
        if (CollectionUtils.isNotEmpty(fireDeviceIds)) {
            FireDeviceQuery fireDeviceQuery = new FireDeviceQuery();
            fireDeviceQuery.setIds(fireDeviceIds);
            List<FireDevice> fireDevices = fireDeviceService.findAll(fireDeviceQuery);
            fireDeviceList.addAll(fireDevices);
        }
        Map<Long, FireDevice> fireDeviceMap = new HashMap<>();
        for (FireDevice device : fireDeviceList) {
            fireDeviceMap.put(device.getId(), device); // 重复的 ID 会被覆盖
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (FireDeviceAuditRecord entity : dataList) {
                FireDevice fireDevice = fireDeviceMap.get(entity.getDeviceId());
                if(fireDevice == null){
                    continue;
                }
                FireDeviceVo fireDeviceVo = fireDeviceService.entityToFullVo(fireDevice,deviceTypeDataDictMap,userMap,codeDataDictMap,idDataDictMap);

                List<Object> rowList = new ArrayList<>();
                rowList.add("" + orderNo);
                rowList.add(fireDeviceVo.getCode());
                rowList.add(fireDeviceVo.getTypeText());
                rowList.add(fireDeviceVo.getPositionText());
                String gmtBuildStr = "";
                if (fireDeviceVo.getGmtBuild() != null) {
                    gmtBuildStr = DateFormatUtils.format(fireDeviceVo.getGmtBuild(), "yyyy-MM");
                }
                rowList.add(gmtBuildStr);
                Integer status = entity.getStatus();
                String statusText = "";
                if (status != null){
                    DeviceAuditRecordStatusEnum statusEnum = DeviceAuditRecordStatusEnum.getByCode(status);
                    statusText = statusEnum.getValue();
                }
                rowList.add(statusText);

                //审核人
                String auditUserName = "";
                Long auditUserId = fireDevice.getAuditUserId();
                if (auditUserId != null) {
                    User user = userMap.get(auditUserId);
                    if(user != null){
                        auditUserName = user.getUserName();
                    }
                }
                rowList.add(auditUserName);
                String gmtAuditStr = "";
                if (entity.getGmtAudit() != null) {
                    gmtAuditStr = DateFormatUtils.format(entity.getGmtAudit(), "yyyy-MM-dd HH:mm:ss");
                }
                rowList.add(gmtAuditStr);
                rowList.add(fireDeviceVo.getArea());
                rowList.add(fireDeviceVo.getWeightType());
                rowList.add(entity.getMemo());
                xlsDataList.add(rowList);
                orderNo++;
            }
        }
        try {
            InputStream templateInputStream = deviceXlsTemplate.getInputStream();
            XlsUtils.export(xlsDataList, "消防检查设备检查汇总表", templateInputStream, response);
        } catch (Exception e) {
            throw new BizException(e);
        }

    }

}
